const { parsePhoneNumberFromString } = require('libphonenumber-js');
const {FileTypeEnum} = require("../model/other/enums");

function isValidDateString(dateStr) {
    // 校验格式 YYYY-MM-DD
    const dateRegex = /^\d{4}-(0[1-9]|1[0-2])-(0[1-9]|[12]\d|3[01])$/;
    if (!dateRegex.test(dateStr)) return false;

    const [year, month, day] = dateStr.split('-').map(Number);

    const monthDays = [31, (isLeapYear(year) ? 29 : 28), 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
    return day <= monthDays[month - 1];
}

function isLeapYear(year) {
    //
    return (year % 4 === 0 && year % 100 !== 0) || (year % 400 === 0);
}

function getEnumKeyByValue(enumObj, value) {
    return Object.keys(enumObj).find(key => enumObj[key] === value) || null;
}

function isValueInEnum(enumObj, value) {
    return Object.values(enumObj).includes(value);
}

function isValidPhoneNumber(number, countryCode) {
    // number: 用户输入的手机号
    // countryCode: 可选，例如 'US', 'CN', 'GB'
    const phoneNumber = parsePhoneNumberFromString(number, countryCode);
    if (!phoneNumber) return false;          // 无效号码
    return phoneNumber.isValid();            // 返回 true / false
}

function isValidPassword(password) {
    // const passwordRegex = /^\d{6}$/;
    // if(!passwordRegex)
}

function addHours(date, hours) {
    return new Date(date.getTime() + hours * 3600 * 1000);
}

function addMinute(data, minute) {
    return new Date(data.getTime() + minute * 60 * 1000);
}

function isAllowedFileType(t) {
    if (!t) return false;
    const sets = [
        ...Object.values(FileTypeEnum.File),
        ...Object.values(FileTypeEnum.IMAGE),
        ...Object.values(FileTypeEnum.VIDEO),
        ...Object.values(FileTypeEnum.AUDIO),
    ];
    return sets.includes(t);
}

module.exports  = {
    isValidDateString,
    getEnumKeyByValue,
    isValueInEnum,
    isValidPhoneNumber,
    addHours,
    addMinute,
    isAllowedFileType}

